﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BlueLotus7.SSQAnalyzeWebApplication.Controllers;
using BlueLotus7.SSQAnalyzeWebApplication.ViewModel;
using BlueLotus7.SSQAnalysisCore;
using BlueLotus7.SSQAnalyzeWebApplication.Properties;

namespace BlueLotus7.SSQAnalyzeWebApplication.Extensions
{
    public static class BinaryOperationExtension
    {
        public static string GenerateHistoryFiles(this HistoryController controller, RetrieveHistoryInfoPageModel model)
        {
            string result = string.Empty;

            if (model != null && model.SSQMartixItems != null
                && !string.IsNullOrWhiteSpace(model.StartStage) && !string.IsNullOrWhiteSpace(model.EndStage))
            {
                string path = GenerateHistoryName(model.StartStage, model.EndStage);
                int index = 0;
                path = Path.Combine(Settings.Default.HistoryFolder, path);
                result = path;
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception ex)
                {
                    throw new Exception("Failed to create path.", ex);
                }

                try
                {
                    while (model.SSQMartixItems.Count - index > 0)
                    {
                        int count = 0;
                        List<SSQMartixItem> items = new List<SSQMartixItem>();
                        while (count < Constants.PageSize)
                        {
                            items.Add(model.SSQMartixItems[index]);
                            count++;
                            index++;
                        }
                        GenerateHistoryFile(controller, items, path);
                    }
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    Directory.Delete(path, true);
                }
            }

            return result;
        }

        private static void GenerateHistoryFile(Controller controller, List<SSQMartixItem> items, string fullFolderPath)
        {
            if (controller != null && items != null && !string.IsNullOrWhiteSpace(fullFolderPath) && items.Count > 0)
            {
                string fileContent = controller.RenderRazorViewToString("SSQMartixView", items.AsReadOnly());
                File.WriteAllText(Path.Combine(fullFolderPath, GenerateHistoryName(items[0].LotteryIdentity, items[items.Count - 1].LotteryIdentity)) + ".html", fileContent);
            }
        }

        private static string GenerateHistoryName(string start, string end)
        {
            return start + "-" + end;
        }
    }
}